﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WebApiV1.Inteface.Log;
using WebApiV1.Utils.Log;

namespace WebApiV1.Utils.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILog _log;

        public GlobalExceptionFilter(ILog log)
        {
            _log = log;
        }

        public void OnException(ExceptionContext context)
        {
            _log.Error(context.Exception);

            if (context.ExceptionHandled == false)
            {
                context.Result = new ContentResult
                {
                    Content = context.Exception.Message,//这里是把异常抛出。也可以不抛出。
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "text/html;charset=utf-8"
                };
            }
            context.ExceptionHandled = true;
        }

        //public Task OnExceptionAsync(ExceptionContext context)
        //{
        //    OnException(context);
        //    return Task.CompletedTask;
        //}

    }
}
